import Storage from 'good-storage'
import {httpGet} from "@/utils/http.js";
import {randString} from "@/utils/libs.js";

const userDataKey = 'USER_INFO_CACHE_KEY'
const adminDataKey = 'ADMIN_INFO_CACHE_KEY'
const systemInfoKey = 'SYSTEM_INFO_CACHE_KEY'

// 检测前台用户session
export function checkSession() {
    return new Promise((resolve,reject) => {
        httpGet("/api/user/session").then(res => {
            resolve(res.data)
        }).catch(e => {
            Storage.remove(userDataKey)
            reject(e)
        })
    })
}

// 检测后台登录用户session
export function checkAdminSession() {
    const item = Storage.get(adminDataKey) ?? {expire:0, data:null}
    // 判断过期时间是否大于当前时间
    if (item.expire > Date.now()) {
        return Promise.resolve(item.data)
    }
    return new Promise((resolve, reject) => {
        httpGet("/api/admin/session").then(res => {
            item.data = res.data
            item.expire = Date.now() + 1000 * 30
            // 存储用户信息
            Storage.set(adminDataKey,item)
            resolve(item.data)
        }).catch(err => {
            Storage.remove(adminDataKey)
            reject(err)
        })
    })
}

// 删除后台用户信息
export function removeAdminInfo() {
    Storage.remove(adminDataKey)
}

// 获取系统配置信息
export function getSystemInfo() {
    const item = Storage.get(systemInfoKey) ?? {expire:0, data:null}
    if (item.expire > Date.now()) {
        return Promise.resolve(item.data)
    }
    return new Promise((resolve, reject) => {
        httpGet("/api/config/get?key=system").then(res => {
            item.data = res
            item.expire = Date.now() + 1000 * 30
            Storage.set(systemInfoKey,item)
            resolve(item.data)
        }).catch(err => {
            reject(err)
        })
    })
}

// 获取客户端ID
export function getClientId() {
    let clientId = Storage.get('client_id')
    if (clientId) {
        return clientId
    }
    // 随机生成客户端Id，并存储起来
    clientId = randString(42)
    Storage.set('client_id',clientId)
    return clientId
}








